<template>

  <div style="background-color: white;border-radius: 10px;margin-top: -10px;height: auto" ref="myDiv">

    <el-dialog
        title="提示"
        :visible.sync="dialogAddImageVisible"
        width="40%"
        :before-close="handleAddImageClose">

      <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
        <el-tab-pane label="我的素材" name="first">
          <el-row>
            <el-col :span="8" v-for="(item,index) in materialList.slice(0,3)" :key="index" style="margin-top: 10px">
              <el-card :body-style="{ padding: '0px' }" style="width: 220px;height: 150px">
                <div class="container">
                  <!--              <img :src="item.url" class="img">-->
                  <el-image
                      style="width: 160px; height: 100px;padding-left: 40px"
                      :src="item.url"
                      fit="contain"></el-image>
                </div>

                <div style="padding: 14px;">
                  <div class="bottom clearfix">
                    <el-checkbox-group v-model="checkList">
                      <el-checkbox :label="item.url">是否添加</el-checkbox>
                    </el-checkbox-group>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8" v-for="(item,index) in materialList.slice(3,6)" :key="index" style="margin-top: 10px">
              <el-card :body-style="{ padding: '0px' }" style="width: 220px;height: 150px">
                <div class="container">
                  <!--              <img :src="item.url" class="img">-->
                  <el-image
                      style="width: 160px; height: 100px;padding-left: 40px"
                      :src="item.url"
                      fit="contain"></el-image>
                </div>

                <div style="padding: 14px;">
                  <div class="bottom clearfix">
                    <el-checkbox-group v-model="checkList">
                      <el-checkbox :label="item.url">是否添加</el-checkbox>
                    </el-checkbox-group>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
          <el-pagination
              @current-change="handleCurrentChange"
              :current-page.sync="currentPage"
              :page-size="6"
              layout="total, prev, pager, next"
              :total="totalCount">
          </el-pagination>
        </el-tab-pane>
        <el-tab-pane label="本地图片" name="second">
          <el-upload
              class="upload-demo"
              drag
              :limit="1"
              action="http://115.159.84.44:24576/wemedia/backend/v1/wemedia/uploadPicture"
              multiple
              :on-exceed="handleExceed"
              :headers="headers"
              :file-list="fileList"
              :on-success="handleSuccess"
              :on-error="handleError"
              :before-upload="customUpload"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">上传png/jpg文件</div>
          </el-upload>
        </el-tab-pane>
      </el-tabs>




      <el-button @click="dialogAddImageVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleAddImageConfirm">确 定</el-button>
    </el-dialog>

    <el-dialog
        title="提示"
        :visible.sync="dialogAddTextVisible"
        width="30%"
        :before-close="handleAddTextClose">
      <el-input
          type="textarea"
          :autosize="{ minRows: 2, maxRows: 4}"
          placeholder="请输入内容"
          v-model="textarea">
      </el-input>
      <div style="height: 30px"></div>
    <el-button @click="dialogAddTextVisible = false">取 消</el-button>
    <el-button type="primary" @click="handleAddTextConfirm">确 定</el-button>
    </el-dialog>

    <el-dialog
        title="提示"
        :visible.sync="dialogEditTextVisible"
        width="30%"
        :before-close="handleEditTextClose">
      <el-input
          type="textarea"
          :autosize="{ minRows: 2, maxRows: 4}"
          placeholder="请输入内容"
          v-model="text">
      </el-input>
      <div style="height: 30px"></div>
      <el-button @click="dialogEditTextVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleEditTextConfirm">确 定</el-button>
    </el-dialog>

    <el-row style="display: flex;justify-content: left">
      <el-input placeholder="请输入文章标题" type="text" id="title" style="border-top-style: none;border-right-style: none;
       border-left-style: none; border-bottom-style:solid;width: 500px;border-bottom-width: 1px;border-bottom-color: #d5d2d2" v-model="title"/>
    </el-row>
    <hr/>
    <el-row style="height: 52vh;overflow-y: auto;">
      <div v-for="(item,index) in dynamicItem" :key="index">
<!--        <span>{{item}}</span>-->
        <div style="display: inline-block" v-if="item.type === 'text'">
          <span >{{item.value}}</span>
          <i class="el-icon-edit" @click="editText(index)"></i>
          <i class="el-icon-plus" @click="addTextItem(index)"></i>
          <i class="el-icon-picture" @click="addImageItem(index)"></i>
          <i class="el-icon-delete" @click="deleteItem(index)"></i>
        </div>
        <div style="display: flex;width: 460px;align-items: center; justify-content: center;padding-left: 600px" v-if="item.type === 'image'">
          <div>
            <el-image :src="item.value" fit="scale-down" style="height: 400px;width: 400px;"/>
          </div>
          <div>
            <i class="el-icon-plus" @click="addTextItem(index)"></i>
            <i class="el-icon-picture" @click="addImageItem(index)"></i>
            <i class="el-icon-delete" @click="deleteItem(index)"></i>
          </div>
        </div>

      </div>


    </el-row>
    <el-row>
      <div>
        <el-button @click="addTextItemAtLast" type="primary">增加文本</el-button>
        <el-button @click="addImageItemAtLast" type="primary">增加图片</el-button>
      </div>
    </el-row>
    <hr/>
    <el-row>
      <div style="display: flex;">
        <span style="width: 40px">标签</span>
        <el-input placeholder="请输入标签" type="text" style="width: 200px;padding-left: 20px" size="small" v-model="labels"></el-input>
        <span style="padding-left: 80px">
          频道
        </span>
        <el-select v-model="value" placeholder="请选择" size="small" style="padding-left: 20px">
        <el-option

            v-for="item in channelList"
            :key="item.channelId"
            :label="item.name"
            :value="item.channelId">
        </el-option>
      </el-select>
        <span class="demonstration">发布时间</span>
        <el-date-picker
            v-model="time"
            type="datetime"
            placeholder="选择日期时间">
        </el-date-picker>

      </div>
    </el-row>
    <br/>
    <el-row>
      <div style="display: flex;padding-left: 5px">
        <span>封面</span>
        <div style="width: 20px"></div>
        <el-upload
            class="upload-demo"
            action="http://115.159.84.44:24576/wemedia/backend/v1/wemedia/uploadPicture"
            :headers="headers"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            multiple
            :limit="1"
            :on-exceed="handleExceedCover"
            :on-success="handleSuccessCover"
            :file-list="fileList">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg文件</div>
        </el-upload>
        <div>
          <img v-if="cover" :src="coverUrl" style="width: 100px;height: 100px"/>
        </div>
        <div style="display: flex;margin-left: 31vw;margin-bottom: 10px" >
<!--          <el-button type="primary" style="height: 40px;width: 100px" @click="publishArticle(0)" v-if="data === null || data.status === null">-->
<!--            <i class="el-icon-folder-opened" style="margin-left: -10px" ></i>-->
<!--            存入草稿-->
<!--          </el-button>-->
          <el-button type="primary" style="height: 40px;width: 100px" @click="publishArticle(1)" >
            <i class="el-icon-top" style="margin-left: -10px"></i>
            提交审核
          </el-button>
        </div>
      </div>
    </el-row>
    <br/>
    <el-row>

    </el-row>
  </div>

</template>

<script>

export default {
  name:'PublishArticle',
  data(){
    return {
      data:null,
      time:null,
      labels:'',
      cover:false,
      coverUrl:'',
      text:'',
      dialogEditTextVisible: false,
      headers:{
        token:localStorage.getItem("token")
      },
      fileList:[],
      activeName: 'first',
      title:'',
      channel:'',
      content:'',
      dynamicItem: [],
      dialogAddTextVisible:false,
      dialogAddImageVisible:false,
      textarea:'',
      clickIndex:0,
      materialList:[],
      currentPage:1,
      totalCount:6,
      checkList:[],
      channelList:[],
      value: ''
    }
  },
  mounted() {
    // console.log("pAheight ",this.$refs.myDiv.offsetHeight)
    // this.$store.commit("transportHeight",this.$refs.myDiv.offsetHeight)
    if(this.$route.query.data === undefined){
      this.data = null
    }else{
      this.data = this.$route.query.data
      this.title = this.data.title
      this.labels = this.data.labels
      this.value = this.data.channelId
      this.status = this.data.status
      this.type = this.data.type
      this.coverUrl = this.data.images
      this.cover = true
      this.dynamicItem = JSON.parse(this.data.content)
      this.time = this.data.publishTime
      // console.log("dy ",this.dynamicItem)
    }
    console.log("data ",this.data)

    this.getChannels()
  },
  methods:{
    getChannels(){
      this.axios.get('http://115.159.84.44:24576/wemedia/backend/v1/wemedia/channels',{
        headers:{
          'token': localStorage.getItem('token')
        }
      }).then((res)=>{
        console.log(res.data.data);
        this.channelList = res.data.data;
        // for (let i = 0; i < this.channelList.length; i++) {
        //   console.log(JSON.stringify(this.channelList[i]))
        // }
        // console.log("频道列表 "+this.channelList)
        this.channelList = this.channelList.filter(channel => channel.name !== "热门");
      });
    },
    publishArticle(status){
      //status = 0 草稿 status = 1 送审
      if(this.title === '' || this.value === '' || this.label === '' || this.dynamicItem.length === 0 || this.coverUrl === ''){
        this.$alert('请填写完整的信息', '有内容遗漏', {
          confirmButtonText: '确定',
        });
        return
      }
      this.axios.post('http://115.159.84.44:24576/wemedia/backend/v1/wemedia/submit',{
        title:this.title,
        channelId:this.value,
        labels:this.labels,
        type:1,
        status:status,
        content:JSON.stringify(this.dynamicItem),
        images:this.coverUrl,
        publishTime:this.time
      },{
        headers: {
          'Content-Type': 'application/json',
          'token':localStorage.getItem("token")
        }
      }).then((res)=>{
        console.log("data ",res.data);
        if(res.data.code === 200){
          this.$message({
            message: '操作成功',
            type:'success'
          });

        }else{
          this.$message.error('操作失败');
        }
        this.$router.push('/myArticle')
      })
    },
    handleSuccessCover(response, file, fileList){
      this.$message({
        message: '恭喜你，上传封面成功',
        type: 'success'
      });
      // console.log("response "+JSON.stringify(response)); // 上传成功后的响应数据
      console.log("data ",response.data.url)
      this.coverUrl = response.data.url
      this.cover = true
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceedCover(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    handleEditTextConfirm(){
      this.dynamicItem[this.clickIndex].value = this.text
      this.dialogEditTextVisible = false
      this.text = ''
    },
    handleEditTextClose(){
      this.dialogEditTextVisible = false
      this.text = ''
    },
    editText(index){
      this.clickIndex = index
      // this.dynamicItem[this.clickIndex].value = "yyy"
      this.dialogEditTextVisible = true
    },
    customUpload(file) {
      const fileType = file.type.toLowerCase();
      const isJpg = fileType === 'image/jpeg' || fileType === 'image/jpg' || fileType === 'image/png';
      if (!isJpg) {
        this.$message.error('只能上传 JPG/PNG 文件');
      }
      return isJpg;
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    handleSuccess(response, file, fileList) {
      // 处理上传成功的逻辑
      this.$message({
        message: '恭喜你，上传成功',
        type: 'success'
      });
      // console.log("response "+JSON.stringify(response)); // 上传成功后的响应数据
      console.log("data ",response.data.url)
      this.dynamicItem.splice(this.clickIndex+1,0,{
        type: 'image',
        value: response.data.url
      })
      this.dialogAddImageVisible = false
      this.fileList = []
    },
    handleError(error, file, fileList) {
      // 处理上传失败的逻辑
      this.$message.error('上传失败');
      console.log(error); // 上传失败的错误信息
      console.log(file); // 当前上传的文件对象
      console.log(fileList); // 已上传的文件列表
      this.fileList = []
    },
    handleClick(tab, event) {
      console.log(tab, event);
    },
    handleCurrentChange(val){
      this.currentPage = val
      console.log("curr ",this.currentPage)
      this.getMyMaterial(this.currentPage)
    },
    getMyMaterial(currentPage){
      this.axios.post('http://115.159.84.44:24576/wemedia/backend/v1/wemedia/list',{
        "page":currentPage,
        "size":6
      },{
        headers:{
          'token': localStorage.getItem('token')
        },
      }).then((res)=>{
        console.log(res.data.data);
        this.materialList = res.data.data
        this.totalCount = res.data.total
      });
    },
    handleAddTextClose(){
      this.dialogAddTextVisible = false

    },
    handleAddTextConfirm(){
      this.dynamicItem.splice(this.clickIndex+1,0,{
        type: 'text',
        value: this.textarea
      })
      this.dialogAddTextVisible = false
      this.textarea = ''


    },
    handleAddImageConfirm(){
      this.dialogAddImageVisible = false
      console.log("checkList",this.checkList)
      for (let i = 0;i < this.checkList.length;i++){
        this.dynamicItem.splice(this.clickIndex+1,0,{
          type: 'image',
          value: this.checkList[i]
        })
      }
      this.checkList = []

    },
    handleAddImageClose(){
      this.dialogAddImageVisible = false
      this.checkList = []
    },
    addTextItem (index) {
      this.clickIndex = index
      this.dialogAddTextVisible = true

    },
    addImageItem(index){
      this.dialogAddImageVisible = true
      this.clickIndex = index
      console.log(this.clickIndex)
      this.axios.post('http://115.159.84.44:24576/wemedia/backend/v1/wemedia/list',{
        "page":this.currentPage,
        "size":6
      },{
        headers:{
          'token': localStorage.getItem('token')
        },
      }).then((res)=>{
        console.log(res.data.data);
        this.materialList = res.data.data
        this.totalCount = res.data.total
      });
      // this.dynamicItem.splice(index+1,0,{
      //   type: 'image',
      //   value: 'http://115.159.84.44:9000/newyouth/2023/12/15/e2f454fa6cb543ab8eb892beb4624d9a.jpg'
      // })
      // console.log(this.dynamicItem)
    },

    addTextItemAtLast () {
      this.clickIndex = this.dynamicItem.length-1
      this.dialogAddTextVisible = true

    },
    addImageItemAtLast(){
      this.dialogAddImageVisible = true
      this.clickIndex = this.dynamicItem.length-1
      console.log(this.clickIndex)
      this.axios.post('http://115.159.84.44:24576/wemedia/backend/v1/wemedia/list',{
        "page":this.currentPage,
        "size":6
      },{
        headers:{
          'token': localStorage.getItem('token')
        },
      }).then((res)=>{
        console.log(res.data.data);
        this.materialList = res.data.data
        this.totalCount = res.data.total
      });
      // this.dynamicItem.splice(index+1,0,{
      //   type: 'image',
      //   value: 'http://115.159.84.44:9000/newyouth/2023/12/15/e2f454fa6cb543ab8eb892beb4624d9a.jpg'
      // })
      // console.log(this.dynamicItem)
    },


    deleteItem (index) {
      this.dynamicItem.splice(index, 1)
    }
  }
}
</script>

<style scoped>
.container {
  width: 160px;
  height: 100px;
  overflow: hidden; /* 防止图片溢出容器 */
}

.container img {
  max-width: 100%;
  max-height: 100%;
}
</style>